package com.cnhaimei.vod.logic;

import java.util.List;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.graphics.drawable.GradientDrawable.Orientation;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.ViewFlipper;

import com.cnhaimei.base.BaseActivity;
import com.cnhaimei.vod.FavoriteManager;
import com.cnhaimei.vod.R;
import com.cnhaimei.vod.bean.Song;
import com.cnhaimei.vod.logic.EventsManager.EventsListener;
import com.cnhaimei.vod.net.DCHeart;
import com.cnhaimei.vod.net.NetManager;
import com.cnhaimei.vod.net.XVod;
import com.cnhaimei.vod.util.Const;
import com.cnhaimei.vod.util.Util;

/**
 * 加载界面 1.网络连接初始化 2.获取包厢数据并进入包厢界面
 * 
 * @author Jin001.Wu@gmail.com <br>
 * @date 2011-7-2
 * 
 */
public class LoadingActivity extends BaseActivity implements EventsListener, OnGestureListener{
	private static final int MSG_TEXT_REFRESH = 1;
	private static final int MSG_GET_ROOMS = 2;
	private static final int MSG_SHOW_PROGRESS = 3;//新的载入方式，在loading界面不处理任何操作，只加载进度条
	private int nProgressRunTimeOnce = 80;//进度条每次加10所用的时间，单位ms
	private static final int GET_ROOMS_TIME = 3500;

	int testCount = 0;

	private ProgressBar mProgressBar;
//	private TextView mProgressText;
	private GestureDetector mDetector;
	private ViewFlipper mHelpFlipper;
	private View mHelpLayout;
	
	private int mHelpFlipperIndex = 0;
	private int mHelpImgCount = 4;
	private boolean mProgressNeedGoOn;//进度条是否继续加长
	private boolean mTypeChooseDialogShowed;//版本选择窗口是否已经显示
	
	// private int mProgressMax;
	private int mTextCount = 0;
	private String[] mTextArray;
	private int dcHeartId;
	private int dqHeartId;
	private int dqManagerId;
	private String[] rooms;
	private boolean dqConnected;
	private boolean roomsGetted;
	private boolean dialogShowed;
	private boolean dqHearConnected;
	
	private static String TAG = "LoadingActivity";

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.v8_loading);
		//this.setContentView(R.layout.test);
		preInitView();
		initView();

		mProgressHandler.sendEmptyMessageDelayed(MSG_SHOW_PROGRESS, nProgressRunTimeOnce);
		//preInitData();
		
		if (!FavoriteManager.G().isLoaded()) {
			try {
				FavoriteManager.G().load();
				/*
				List<Song> list = FavoriteManager.G().getList();
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						Log.d(TAG, String.format("song'name = %s", list.get(i).getName()));
					}
				}
				
				if (FavoriteManager.G().isLoaded()) {
					Song song = new Song("菊花台", "周杰伦", "jay's jht");
					FavoriteManager.G().addSong(song);
					FavoriteManager.G().save();
				}
				
				FavoriteManager.G().load();
				list = FavoriteManager.G().getList();
				if (list != null) {
					for (int i = 0; i < list.size(); i++) {
						Log.d(TAG, String.format("song'name = %s", list.get(i).getName()));
					}
				}
				*/
				
			} catch (Exception e) {
				// TODO: handle exception
				Log.e(TAG, e.getMessage());
			}
		}
	}
	
	private void preInitView() {
		DCHeart.setNetCard(getLocalMacAddress());
		if (Util.TEST || Util.DEMO) {
			roomsGetted = false;
		}
	}
	
	private void preInitData()	{
		boolean isFirstLaunch = Util.getIsFirstLaunch(this);
		if (isFirstLaunch) {//第一次启动显示帮助页
			mDetector = new GestureDetector(this);
			drawHelpBackground();
			showHelp(true);
		}
		else {//跳转到主界面
			initData();
		}
	}
	
	private void showHelp(boolean show) {
		mHelpLayout.setVisibility(show ? View.VISIBLE : View.GONE);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		return this.mDetector.onTouchEvent(event);
	}

	public boolean onDown(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}

	public boolean onFling(MotionEvent e1, MotionEvent e2, float arg2,
			float arg3) {
		Log.i("Fling", "Fling Happened!");
		if (e1.getX() - e2.getX() > 5) {
			this.mHelpFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_left_in));
			this.mHelpFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_left_out));
			if (mHelpFlipperIndex < mHelpImgCount - 1) {
				this.mHelpFlipper.showNext();
				mHelpFlipperIndex++;
				//TODO:若有点号索引，则可在此处理
			}
			else {//达到最后一页，在翻页则退出。
				showHelp(false);
				Util.setIsFirstLaunch(this, false);
				//initData();
				gotoHomeActivity();
			}

			return true;
		} else if (e1.getX() - e2.getX() < -5) {
			this.mHelpFlipper.setInAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_right_in));
			this.mHelpFlipper.setOutAnimation(AnimationUtils.loadAnimation(this,
					R.anim.push_right_out));
			if (mHelpFlipperIndex > 0) {
				this.mHelpFlipper.showPrevious();
				mHelpFlipperIndex--;
				//TODO:若有点号索引，则可在此处理
			}
			return true;
		}
		return true;
	}

	public void onLongPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public boolean onScroll(MotionEvent arg0, MotionEvent arg1, float arg2,
			float arg3) {
		// TODO Auto-generated method stub
		return false;
	}

	public void onShowPress(MotionEvent arg0) {
		// TODO Auto-generated method stub
		
	}

	public boolean onSingleTapUp(MotionEvent arg0) {
		// TODO Auto-generated method stub
		return false;
	}
	
    public void drawHelpBackground()
    {
    	GradientDrawable grad = new GradientDrawable( 
    			   Orientation.TL_BR,
    			   new int[] {Color.rgb(0, 0, 127),
    					   Color.rgb(0, 0, 255),
    					   Color.rgb(127, 0, 255),
    					   Color.rgb(127, 127, 255),
    					   Color.rgb(127, 255, 255),
    					   Color.rgb(255, 255, 255)} 
    	); 

    	mHelpLayout.setBackgroundDrawable(grad);
    }
	
	private String getLocalMacAddress() {   
		WifiManager wifi = (WifiManager) getSystemService(   
		Context.WIFI_SERVICE);   
		WifiInfo info = wifi.getConnectionInfo();   
		return info.getMacAddress();   
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		if (isFinishing()) {
			mProgressHandler.removeMessages(MSG_GET_ROOMS);
			mProgressHandler.removeMessages(MSG_TEXT_REFRESH);
			EventsManager.G().unRegisterListener(EventsManager.Event.CONNECTING,
					this);
			EventsManager.G().unRegisterListener(EventsManager.Event.ROOMS, this);
		}
	}


	@Override
	protected void onDestroy() {
		super.onDestroy();
	}
	
	private void gotoHomeActivity()
	{
		finish();
		startActivity(new Intent(Const.Action.Home));
	}

	private void initView() {
		mHelpLayout = (View) findViewById(R.id.help_layout);
		mHelpFlipper = (ViewFlipper)findViewById(R.id.help_viewflipper);
		mProgressBar = (ProgressBar)findViewById(R.id.progress);
		//TODO:根据不同分比率设置不同的paddingTop

		DisplayMetrics dMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dMetrics);
		int nRO = getRequestedOrientation();
		View textview01 = findViewById(R.id.textview01);
		RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)textview01.getLayoutParams();
		if (ActivityInfo.SCREEN_ORIENTATION_PORTRAIT == nRO) {//竖屏
			lp.setMargins(0, dMetrics.heightPixels * 3 / 4, 0, 0);
		}
		else {//横屏
			lp.setMargins(0, dMetrics.heightPixels * 3 / 4, 0, 0);
		}
		mProgressBar.setProgress(0);
	}

	private void initData() {
		//为选择对话框设置在loading界面。目前此方式已被弃用
		
		mProgressNeedGoOn = false;
		mTypeChooseDialogShowed = false;
		
		EventsManager.G().registerListener(EventsManager.Event.ROOMS, this);
		EventsManager.G().registerListener(EventsManager.Event.CONNECTING, this);
		 dcHeartId = NetManager.G().startDCHeart(); // 启动网络
		 dqHeartId = NetManager.G().startDQHeart(); // need
		mProgressHandler.sendEmptyMessageDelayed(MSG_TEXT_REFRESH, 50);
		
	}

	private void requestGetRooms() {
		XVod.G().downloadRooms();
		mProgressHandler.sendEmptyMessageDelayed(MSG_GET_ROOMS, GET_ROOMS_TIME);
	}

	//“单机版”和“网络版”选择框
	private void showTypeChooseDialog()
	{
		mTypeChooseDialogShowed = true;
		new AlertDialog.Builder(this)
        /* 弹出窗口的最上头文字 */
        .setTitle(R.string.tip_title)
        /* 设置弹出窗口的信息 */
        .setMessage(R.string.type_choose_msg)
        .setPositiveButton(R.string.type_net_ver,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                        //TODO：执行网络版操作
                    	mProgressNeedGoOn = true;
                    	mTypeChooseDialogShowed = false;
                		mProgressHandler.sendEmptyMessageDelayed(MSG_TEXT_REFRESH, 500);
                    }
                })
        .setNegativeButton(R.string.type_local_ver,
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialoginterface, int i) {
                    	//TODO：执行单机版操作
                    	mProgressNeedGoOn = true;
                    	mTypeChooseDialogShowed = false;
                		mProgressHandler.sendEmptyMessageDelayed(MSG_TEXT_REFRESH, 500);
                    }
                })
        .setOnKeyListener(new DialogInterface.OnKeyListener() {			
			public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
                if (keyCode == KeyEvent.KEYCODE_BACK  
                        && event.getRepeatCount() == 0) { 
                    return true;
                }  
				return false;
			}
		})
        .show();

	}
	
	private void refreshProgressBar() {
		if (mTypeChooseDialogShowed) {
			return;
		}
		mProgressHandler.sendEmptyMessageDelayed(MSG_TEXT_REFRESH, 500);
		testCount++;
		
		int cur = mProgressBar.getProgress();
		if (!mProgressNeedGoOn && cur >= mProgressBar.getMax() / 2) {
			showTypeChooseDialog();
			return;
		} else {
			mProgressBar.setProgress(mProgressBar.getProgress() + 10);
		}

		if (testCount > 10) {
//			loaddingFinished();
			checkAndEnter(true); 
		}
	}

	private void refreshProgressText() {
		mTextCount++;
	}

//	private void loaddingFinished() {
//		mProgressHandler.removeMessages(MSG_TEXT_REFRESH);
//		startActivity(Const.Action.LoadingFinsihed);
//		finish();
//	}

	private void OnProgressEnd()
	{
		boolean isFirstLaunch = Util.getIsFirstLaunch(this);
		if (isFirstLaunch) {//第一次启动显示帮助页
			mProgressBar.setVisibility(View.INVISIBLE);
			mDetector = new GestureDetector(this);
			drawHelpBackground();
			showHelp(true);
		}
		else
		{
			gotoHomeActivity();
		}
	}
	
	private Handler mProgressHandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MSG_SHOW_PROGRESS://
				{				
					int cur = mProgressBar.getProgress();
					if (cur >= mProgressBar.getMax()) {
						OnProgressEnd();
						return;
					}

					mProgressBar.setProgress(mProgressBar.getProgress() + 10);
					mProgressHandler.sendEmptyMessageDelayed(MSG_SHOW_PROGRESS, nProgressRunTimeOnce);	
				}
				break;
			case MSG_TEXT_REFRESH://【不再采用】
				refreshProgressBar();
				refreshProgressText();

				// replay
				break;
			case MSG_GET_ROOMS://【不再采用】
				requestGetRooms();
				break;
			default:
				break;
			}
		}

	};

	public void onEvent(int event, Object obj, boolean isSuc) {
		switch (event) {
		case EventsManager.Event.CONNECTING: {
			if (obj != null && obj instanceof Integer) {
				int id = (Integer) obj;
				if (id == dcHeartId) {
					requestGetRooms(); // 请求房间数据
				} else if (id == dqHeartId && !dqHearConnected) {
					dqHearConnected = true;
					dqManagerId = NetManager.G().startDQManger();
				} else if (id == dqManagerId && !dqConnected) {
					Log.e("LoadingActivity", "dqmanagerid");
					dqConnected = true;
					// loaddingFinished();
					// Intent i = new Intent(Const.Action.LoadingFinsihed);
					// i.putExtra(Const.Key.ROOM_LIST, rooms);
					// startActivity(i);
					checkAndEnter(false);
				}
			}
		}
			break;
		case EventsManager.Event.ROOMS:
			if (isSuc && obj != null && rooms == null) {
				EventsManager.G().unRegisterListener(event, this);
				rooms = (String[]) obj;
				mProgressHandler.removeMessages(MSG_GET_ROOMS);
				roomsGetted = true;
				checkAndEnter(false);
			}
			break;
		default:
			break;
		}
	}
	
	private void checkAndEnter(boolean showDialog) {
		if (dialogShowed) {
			return;
		}
		if (dqConnected && roomsGetted) {
			mProgressHandler.removeMessages(MSG_TEXT_REFRESH);
			 Intent i = new Intent(Const.Action.LoadingFinsihed);
			 i.putExtra(Const.Key.ROOM_LIST, rooms);
			 startActivity(i);
			 finish();
		} else if (showDialog) {
			dialogShowed = true;
			mProgressHandler.removeMessages(MSG_TEXT_REFRESH);
			if (!dqConnected) {
				showErrorDialog(R.string.connecting_dq_error);
			} else {
				showErrorDialog(R.string.get_rooms_error);
			}
		}
	}
	
	private void showErrorDialog(int tipRes) {
		AlertDialog.Builder b = new AlertDialog.Builder(this);
		b.setTitle(R.string.loading_fail);
		b.setIcon(android.R.drawable.ic_dialog_info);
		b.setMessage(tipRes);
		b.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				Util.exit();
			}
		});
		b.setCancelable(false);
		b.show();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_BACK:
			Util.exit();
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

}